<style lang='scss' scoped>
.list-detail {
  display: flex;
  flex-flow: column;
  padding: 8px 0;
  height: 100%;
  .book-info {
    flex: 1;
    padding: 10px;
    background-color: #fff;
    .book-info_item {
      color: #999;
      padding: 5px;
      .title {
        color: #333;
        font-size: 22px;
        font-weight: 500;
      }
      .book-info_item-list {
        position: relative;
        width: 90%;
        border-bottom: 1px dashed #ccc;
        .delete-icon {
          text-align: center;
          font-size: 20px;
          position: absolute;
          width: 10%;
          height: 60px;
          right: -13%;
          bottom: 0px;
        }
      }
      .item_add {
        margin: 20px;
      }
    }
  }
}
</style>
<template>
  <div class="list-detail">
    <div class="c-book-piece" style="min-height: 120px">
      <div class="cover-image">
        <image :src="form.img || '../../static/book.png'" mode="aspectFit" />
      </div>
      <div class="detail-box">
        <span class="title">{{ form.bookName }}</span>
        <span class="sub-title">
          <span class="sub-title-left">{{ form.bookVersion }}</span>
        </span>
        <span class="desc desc-line-3">{{ form.desc }}</span>
        <div class="footer-bar">
          <span class="sale-price">书号: {{ form.bookNumber || '-' }}</span>
          <span class="price">定价￥{{ form.bookPrice || '-' }}</span>
        </div>
        <div class="book-count">{{ form.bookAuthor }}</div>
      </div>
    </div>
    <div class="book-info">
      <div class="book-info_item">
        <div class="title">主要用书信息</div>
        <u-form :model="form" ref="uForm" label-width="200">
          <u-form-item label="教师用书数量" prop="teacherBookNum">
            <u-input
              type="number"
              v-model="form.teacherBookNum"
              placeholder="请输入教师用书数量"
            />
          </u-form-item>
          <u-form-item label="学期" prop="semester">
            <u-radio-group v-model="form.semester">
              <u-radio
                v-for="(item, index) in [
                  { key: '1', name: '春季' },
                  { key: '2', name: '秋季' }
                ]"
                :key="index"
                :name="item.key"
              >
                {{ item.name }}
              </u-radio>
            </u-radio-group>
          </u-form-item>
        </u-form>
      </div>
      <div class="book-info_item">
        <div class="title">学生用书详情</div>
        <u-form :model="form" ref="form" label-width="150">
          <div
            class="book-info_item-list"
            v-for="(item, index) in form.orderBookInfos"
            :key="index"
          >
            <u-form-item
              label="课程名称"
              :prop="'orderBookInfos.' + index + '.courseName'"
              style="width: 80%"
            >
              <u-input placeholder="请输入课程名称" v-model="item.courseName" />
            </u-form-item>
            <u-form-item
              label="年级专业"
              :prop="'orderBookInfos.' + index + '.majorId'"
            >
              <div @click="showSelect(item)">
                <span v-if="item.grade || item.majorName">
                  {{ item.grade + '级 - ' + item.majorName }}</span
                >
                <span v-else>请选择年级专业</span>
              </div>
              <u-select
                v-model="item.showSelect"
                mode="mutil-column"
                :list="multiSelector"
                value-name="majorId"
                label-name="majorName"
                @confirm="(e) => multiData(e, index)"
              ></u-select>
            </u-form-item>
            <u-form-item
              label="用书量"
              :prop="'orderBookInfos.' + index + '.bookNum'"
              style="width: 80%"
            >
              <u-input placeholder="请输入所需数量" v-model="item.bookNum" />
            </u-form-item>
            <u-icon
              v-if="form.orderBookInfos.length > 1"
              class="delete-icon"
              name="trash"
              @click="removeDomain(item)"
            ></u-icon>
          </div>
          <div class="item_add">
            <u-button @click="addDomain">
              <u-icon name="plus"></u-icon>添加年级专业
            </u-button>
          </div>
        </u-form>
        <u-button type="primary" @click="sumbit">提交</u-button>
      </div>
    </div>
  </div>
</template>
<script>
import * as api from '../../common/api.js'

export default {
  data() {
    return {
      form: {
        bookId: '',
        bookNums: '',
        teacherBookNum: '',
        semester: '1',
        orderBookInfos: [
          {
            majorName: '',
            courseName: '',
            showSelect: false,
            majorId: '',
            grade: '',
            bookNum: ''
          }
        ]
      },
      multiSelector: [[], []],
      rules: {
        teacherBookNum: [
          {
            required: true,
            type: 'number',
            message: '不能为空',
            trigger: 'blur,change'
          },
          {
            validator: (rule, value, callback) => {
              if (value) {
                return this.$u.test.digits(value)
              }
            },
            message: '大于零的整数',
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  async onLoad(option) {
    wx.showLoading({ title: '加载中...' })
    try {
      this.multiSelector = [this.getYearList(), await this.getMajor()]
      if (option.bookItem) {
        this.type = 'add'
        Object.assign(this.form, JSON.parse(option.bookItem))
      }
      if (option.orderList) {
        const order = JSON.parse(option.orderList)
        order.orderBookInfos.forEach((item) => {
          item.showSelect = false
        })
        Object.assign(this.form, order)
      }
    } catch (e) {
      console.log(e)
    } finally {
      wx.hideLoading()
      uni.stopPullDownRefresh()
    }
  },

  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  methods: {
    showSelect(item) {
      item.showSelect = true
    },
    addDomain() {
      this.form.orderBookInfos.push({
        majorName: '',
        courseName: '',
        showSelect: false,
        majorId: '',
        grade: '',
        bookNum: ''
      })
    },
    removeDomain(item) {
      let index = this.form.orderBookInfos.indexOf(item)
      if (index !== -1) {
        this.form.orderBookInfos.splice(index, 1)
      }
    },
    multiData(e, index) {
      this.form.orderBookInfos[index].majorId = e[1].value
      this.form.orderBookInfos[index].grade = e[0].value
      this.form.orderBookInfos[index].majorName = e[1].label
    },
    sumbit() {
      this.$refs.uForm.validate(async (valid) => {
        this.form.bookNums = 0
        this.form.orderBookInfos.forEach((item) => {
          if (!item.courseName) {
            wx.showToast({
              title: '课程名称不能为空',
              icon: 'none',
              duration: 1000
            })
            valid = false
          } else if (!item.majorName) {
            wx.showToast({
              title: '必须选择年级专业',
              icon: 'none',
              duration: 1000
            })
            valid = false
          } else if (!+item.bookNum) {
            wx.showToast({
              title: `请填写正确的${item.courseName}所需数量`,
              icon: 'none',
              duration: 1000
            })
            valid = false
          } else {
            this.form.bookNums = +item.bookNum + this.form.bookNums
          }
        })
        if (valid) {
          if (this.type === 'add') {
            await api.addOrderInfo(this.form)
          } else {
            await api.updateOrderInfo(this.form)
          }
          wx.switchTab({
            url: `/pages/User/User`,
            success: function (e) {
              var page = getCurrentPages().pop()
              if (page == undefined || page == null) return
              page.onLoad()
            }
          })
        } else {
          console.log('验证失败')
        }
      })
    },
    async getMajor() {
      const schoolId = wx.getStorageSync('schoolId')
      if (schoolId) {
        return await api.getMajor(schoolId)
      }
    },
    getYearList() {
      var nfOptionsArray = new Array()
      var years = new Date().getFullYear()
      for (var i = years - 5; i <= years + 1; i++) {
        var anOption = {}
        anOption.majorId = i
        anOption.majorName = i + '级'
        nfOptionsArray.push(anOption)
      }
      return nfOptionsArray
    }
  }
}
</script>